package com.zyh.homework.test1;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author zyh
 * @Date 2024/8/13 19:04
 * @Description 使用java创建xml文件
 */

public class Test1 {
    public static void main(String[] args) throws IOException {
        Document document = DocumentHelper.createDocument();
        //添加根节点元素
        Element rootElement = document.addElement("bookstore");
        //通过根节点添加子元素
        Element book1 = rootElement.addElement("book");
        //子元素的属性
        book1.addAttribute("category","科幻");
        //添加孙子节点
        Element title1 = book1.addElement("title");
        //添加孙子节点的属性
        title1.addAttribute("lang","english");
        //添加孙子节点的内容
        title1.addText("harrypotter");
        Element author1 = book1.addElement("author");
        author1.addText("rowling");
        Element year1 = book1.addElement("year");
        year1.addText("2000");
        Element price1 = book1.addElement("price");
        price1.addText("29.99");

        //添加第二个子元素
        //通过根节点添加子元素
        Element book2 = rootElement.addElement("book");
        //子元素的属性
        book2.addAttribute("category","it");
        //添加孙子节点
        Element title2 = book2.addElement("title");
        //添加孙子节点的属性
        title2.addAttribute("lang","chinese");
        //添加孙子节点的内容
        title2.addText("java");
        Element author2 = book2.addElement("author");
        author2.addText("james gosling");
        Element year2 = book2.addElement("year");
        year2.addText("1995");
        Element price2 = book2.addElement("price");
        price2.addText("50");

        OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
        //写到指定文件
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\homework\\test1\\test.xml"),prettyPrint);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}
